package com.test.case5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:wyf
 * @Description:ReentrantLock主要利用CAS+AQS队列来实现。它支持公平锁和非公平锁，两者的实现类似  耗时比Counter1长
 * @Date:Created in 11:14 2021/6/29
 * @Modified By:
 */
public class Counter2 {
    public static int inc = 0;
    Lock lock = new ReentrantLock();

    public void increase(){
        lock.lock();
        try{
            inc++;
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            inc = 0;
            count();
        }
    }

    public static void count() throws InterruptedException {
        Counter2 c2 = new Counter2();
        Thread th = null;
        Long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            th = new Thread(){
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        c2.increase();
                    }
                }
            };
            th.start();
            //让其他线程停止运行，自己运行线程
            th.join();
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Counter2 , "+String.format("结果：%s,耗时(ms)：%s", c2.inc, (t2 - t1)));
    }
}
